////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   COMPANY
// AUTHOR           :   Victor Zheng 
// DATE CREATE      :   2006/02/01
// DESCRIPTION      :   a MAINTENANCE ACTION file for the function, COMPANY
//                  :   
//                  :   
//                  :   
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2006/02/01   Victor Zheng    1.0                 source is generated.
//
//
//
////////////////////////////////////////////////////////////////////////////////

package com.erp.app.admin.companySetup.web;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.erp.app.admin.companySetup.pk.CompanyPk;
import com.erp.app.admin.companySetup.schema.CompanySchema;
import com.erp.app.admin.companySetup.vo.CompanyVo;
import com.erp.app.common.ProjectConstants;
import com.erp.app.util.web.WebUtil;
import com.erp.framework.controller.action.SimpleMaintStyleAction;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

/**
* A <strong>Maintenance Action</strong> is an adapter between the contents of an incoming
* HTTP request and the corresponding business logic that should be executed to
* process this request.  The controller (ActionServlet) will select an
* appropriate Action for each request.
* The main purpose for this action class is to handle the user document maintenance events
* from the web browsers.
*
* @author          Victor Zheng 
* @version 1.0     2006/02/01
* @since           FrameWork 1.0
*
*/
public class CompanyMaintenanceAction extends SimpleMaintStyleAction {

	////////////////////////////////////////////////////////////////////////////////
	// CONSTANTS DEFINITION
	////////////////////////////////////////////////////////////////////////////////

	public static final String ACTION_ADD_COMP_LOGO = "addCompLogo";
    public static final String ACTION_VIEW_COMP_LOGO = "viewCompLogo";
    public static final String ACTION_DEL_COMP_LOGO = "delCompLogo";
    public static final String STATUS_ADD_COMP_LOGO = "addCompLogo_set";

	////////////////////////////////////////////////////////////////////////////////
	// GLOBAL VARIABLES DEFINITION
	////////////////////////////////////////////////////////////////////////////////



	////////////////////////////////////////////////////////////////////////////////
	// LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////

	public ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			if (!isHandled(request) && action.equalsIgnoreCase(ACTION_ADD_COMP_LOGO)) {
	            setHandled(request);
	            actionForward = processActionAddCompLogo(mapping, form, request, response, errors);
	        } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_VIEW_COMP_LOGO)) {
	            setHandled(request);
	            actionForward = processActionViewCompLogo(mapping, form, request, response, errors);
	        } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_DEL_COMP_LOGO)) {
	            setHandled(request);
	            actionForward = processActionDelCompLogo(mapping, form, request, response, errors);
	            saveToken(request);
	        }
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}

		return actionForward;
	}

	protected ActionForward processOtherStatus(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response,
		ActionErrors errors, String rb_status) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			if (rb_status.equalsIgnoreCase(STATUS_ADD_COMP_LOGO)) {
				return processStatusAddCompLogo(mapping,  form,  request, response,  errors,  rb_status);
			}
		} catch (Exception e) {
			Logger.log(this, e);
		}

		return actionForward;
	}
	
	private ActionForward processActionAddCompLogo(ActionMapping mapping, CompanyMaintenanceForm form,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        ActionForward actionForward = new ActionForward(mapping.getInput());

        HashMap params = new HashMap();
        LinkedList keyList = new LinkedList();

        keyList.add("Company Code");
        keyList.add(form.getCompanyCode());

        String status = STATUS_ADD_COMP_LOGO;

        params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_NAME, getSessionSimpleMaintStatus());
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_VALUE, status);
        params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
        session.setAttribute(ProjectConstants.SESSION_UPLOAD_FILE_PARAM, params);

        return actionForward;
    }

    private ActionForward processStatusAddCompLogo(ActionMapping mapping, CompanyMaintenanceForm form,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors, String rb_status) {
        ActionForward actionForward = new ActionForward(mapping.getInput());
        HttpSession session = request.getSession(false);
        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        try {
            HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);
            session.removeAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);

            if (params == null)
                return actionForward;

            FormFile file = (FormFile) params.get(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_FORM_FILE);

            if (file == null)
                return actionForward;

            // retrieve the file name
            String fileName = file.getFileName();

            // retrieve the content type
            String contentType = file.getContentType();

            // retrieve the file data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream stream = file.getInputStream();

            if (!CommonUtil.isEmpty(fileName)) {
//                if (!contentType.equalsIgnoreCase("image/bmp") && !contentType.equalsIgnoreCase("image/jpg")
//                        && !contentType.equalsIgnoreCase("image/gif")) {
//                    errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.image.contentType", "(bmp, jpg, gif)"));
//                    return actionForward;
//                }

                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }

                form.setContentType(contentType);
                form.setCompanyLogo(baos.toByteArray());
            }
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.toString()));
        }
        return actionForward;
    }
    
    private ActionForward processActionViewCompLogo(ActionMapping mapping, CompanyMaintenanceForm form,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        ActionForward actionForward = null;

        try {
            OutputStream out = response.getOutputStream();
            response.setContentType(form.getContentType());
            response.setStatus(HttpServletResponse.SC_OK);
            byte[] content = form.getCompanyLogo();
            out.write(content);
            out.close();
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        return actionForward;
    }
    
    private ActionForward processActionDelCompLogo(ActionMapping mapping, CompanyMaintenanceForm form,
            HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {
        ActionForward actionForward = new ActionForward(mapping.getInput());

        form.setContentType("");
        form.setCompanyLogo(null);

        return actionForward;
    }
    
	////////////////////////////////////////////////////////////////////////////////
	// END OF LOGICAL AND BUSINESS METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// OVERRIDES PARENT'S OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////

	protected void initAction(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initAction(mapping, formIn, request, response, errors);

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
			HashMap errMsgMap = WebUtil.getModuleErrorMessages(editingUser.getCompanyCode(),
				DBMENU_GENERAL_MENU, form.getModuleName(), form.getSysLangCode(), DBMENU_OBJECT_TYPE_ERR_MSG);
			form.setErrMsgMap(errMsgMap);

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void initForm(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initForm(mapping, formIn, request, response, errors);

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void initPage(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		super.initPage(mapping, formIn, request, response, errors);

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeCreate(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {
//			form.setCompanyCode(WebUtil.getAppropriateCompanyCode(session, ProjectConstants.SP_SHARE_COMPANY_SETUP));
			form.setTs(new CompanySchema());
			form.setTsName("com.erp.app.admin.companySetup.schema.CompanySchema");
		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeSave(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterSave(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeEdit(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterEdit(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeDelete(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterDelete(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void beforeRefresh(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	protected void afterRefresh(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request, HttpServletResponse response, ActionErrors errors) {

		HttpSession session = request.getSession(false);
		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		String action = form.getPageEvent();
		ActionForward actionForward = new ActionForward(mapping.getInput());
		User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

		try {

		} catch (Exception e) {
			Logger.logExceptions(this, e);
		}
	}

	public String getSessionMaintStatus() {

		return getSessionSimpleMaintStatus();
	}

	public String getSessionMaintPk() {

		return getSessionSimpleMaintPk();
	}

	public String getStrutsId() {

		return getFunctionId();
	}

	public String getSimpleFormReadOnlySessionName(){

		return ProjectConstants.SESSION_COMPANY_FORM_READ_ONLY_SESSION_NAME;
	}

	public String getSimpleFormReadOnlyCallerSessionName(){

		return ProjectConstants.SESSION_COMPANY_FORM_READ_ONLY_CALLER_SESSION_NAME;
	}

	protected String getSimpleSrchMenuId() {

		return ProjectConstants.MOD_COMPANY_SETUP;
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF OPTIONAL METHODS
	////////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////////
	// IMPLEMENTS PARENT'S ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////

	protected String getModuleName(ActionMapping mapping, ActionForm formIn,
		HttpServletRequest request,HttpServletResponse response) {

		return ProjectConstants.MOD_COMPANY_SETUP;
	}

	protected String getFunctionId() {

		//struts-config xxxxx.do
		return "companyMaintenance.do";
	}

	protected Class getMasterFormClass() {

		//the corresponding form class
		return CompanyMaintenanceForm.class;
	}

	protected Class getMasterVOClass() {

		//corresponding master vo class
		return CompanyVo.class;
	}

	protected String getMasterFormSessionName() {

		return "companyMaintenanceForm";
	}

	protected Class[] getChildRowClass() {

		Class[] childRowClass = new Class[0];


		return childRowClass;
	}

	protected String[] getFolderChildIdxMapping() {

		String[] folderChildIdx = new String[1];


		return folderChildIdx;
	}

	protected SimpleBasePk getPk(ActionForm formIn, HttpServletRequest request) {

		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		CompanyPk pk = null;
		HttpSession session = request.getSession(false);

		String companyCode = WebUtil.getAppropriateCompanyCode(session, ProjectConstants.SP_SHARE_COMPANY_SETUP);

		pk = new CompanyPk(companyCode);
		return pk;
	}

	protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
		HttpServletResponse response, ActionErrors errors){

		CompanyMaintenanceForm form = (CompanyMaintenanceForm) formIn;
		form.setFormType(ProjectConstants.FORM_TYPE_MAINT);
	}

	////////////////////////////////////////////////////////////////////////////////
	// END OF ABSTRACT METHODS
	////////////////////////////////////////////////////////////////////////////////
}
